package com.adminserver.util.rsaUtil;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.adminserver.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.security.KeyPair;
import java.util.HashMap;

@Slf4j
@Component
public class GenerateKey {

    Jedis redis = RedisUtil.getRedis();

    public static final int DB = 1;

    public static final String KEY_NAME = "adminServer_key";

    public static final String PUBLIC = "public";

    public static final String PRIVATE = "private";

    public static HashMap<String, String> cacheKey = new HashMap<>(2);

    /**
     * 密钥生成器-核心
     *
     * @return
     */
    private final HashMap<String, String> generator() {
        try {
            KeyPair pair = SecureUtil.generateKeyPair("RSA");
            String publicKey = Base64.encode(pair.getPublic().getEncoded());
            String privateKey = Base64.encode(pair.getPrivate().getEncoded());
            HashMap<String, String> map = new HashMap<>();
            map.put(PUBLIC, publicKey);
            map.put(PRIVATE, privateKey);
            redis.select(DB);
            redis.set(KEY_NAME, JSON.toJSONString(map));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 密钥检测/创建--项目启动依赖加载完毕 自动执行一次且只执行一次。
     * 初始化项目密钥
     */
    @PostConstruct
    private void createKey() {
        redis.select(DB);
        if (redis.exists(KEY_NAME)) {
            // 装配密钥
            cacheKey.putAll(getKey());
            log.info("系统在Redis {} 号库中检测密钥 {} 成功，密钥装配至{}", DB, KEY_NAME, cacheKey.getClass().getName());
            return;
        }
        generator();
        log.info("系统未检测到 {} 密钥，已在Redis {} 号库中创建 {} 密钥成功", KEY_NAME, DB, KEY_NAME);
    }

    /**
     * 获取缓存密钥
     *
     * @return 密钥对
     */
    public HashMap<String, String> getKey() {
        redis.select(DB);
        return JSON.parseObject(redis.get(KEY_NAME), HashMap.class);
    }

    /**
     * 更新缓存密钥
     *
     * @return 密钥对
     */
    public HashMap<String, String> updateKey() {
        return generator();
    }
}
